#include <thread>
#include <iostream>
#include <mutex>
#include <condition_variable>

std::mutex data_mutex;
std::condition_variable data_var;
bool flag=true;
bool flag1=false;
bool flag2=false;
int i=0;
int a;
int arr[10];
#define MAXNUM 20



void first(){
    while(i<MAXNUM){
        std::this_thread::sleep_for(std::chrono::seconds(1)); //打印节奏变慢
        std::unique_lock<std::mutex> lck(data_mutex); 
        data_var.wait(lck, []{return flag;}); 
        std::cout<<"threadA:";
        a=rand()%1000;
        std::cout<<a;
        flag=false;
        flag1=true;
        flag2=false;
        data_var.notify_all();
        
    }
    std::cout<<"finish A"<<std::endl;
    
}

void second(){
    while(i<=MAXNUM){
        std::unique_lock<std::mutex> lck(data_mutex);
        data_var.wait(lck, []{return flag1;});
        std::cout<<"threadB:"<<std::endl;
        arr[i%10]=a;
        i++;
        if(i%10==0){
            flag=false;
            flag1=false;
            flag2=true;
            data_var.notify_all();
        }
        else{
            flag = true;
            flag1=false;
            flag2=false;
            data_var.notify_all();

        }
        

    }
    std::cout<<"finish B"<<std::endl;
}
void third(){
    while(i<MAXNUM){
        std::unique_lock<std::mutex> lck(data_mutex);
        data_var.wait(lck, []{return flag2;});
        std::cout<<"threadC:"<<std::endl;
        int sum=0;
        float ave=0;
        for(int k=0;k<10;k++){
            std::cout<<"第"<<k<<"个数："<<arr[k]<<std::endl;
            sum+=arr[k];
        }
        ave=float(sum/10);
        std::cout<<"平均数为："<<ave<<std::endl;
        std::cout<<"总和为："<<sum<<std::endl;
        flag = true;
        flag1=false;
        flag2=false;
        data_var.notify_all();
    }
    std::cout<<"finish C"<<std::endl;

}

int main(){
    std::thread tA(first);
    std::thread tB(second);
    std::thread tC(third);
    tA.join();
    tB.join();
    tC.join();
    return 0;
}